import * as React from 'react';
import { Props } from '../type';
import { GenerateUUID, GenerateUUID32 } from '@/utils';
import { connect } from 'react-redux';
import { Toast } from 'antd-mobile-v2';
import _ from 'lodash';
import { DOCUMENT_TYPE_LIST } from '@/pages/official-doc/constants';
import { ConnectState, ConnectProps } from 'typings/connect';
import { APPROVAL_STATUS } from '@/pages/declare/constants';
import { applyType } from '@/constants';

interface CellProps {
  [propsname: string]: any;
}
class GroupOfficialOnlineCpt extends React.Component<Props & ConnectProps, any> {
  id?: string;
  constructor(props: Props) {
    super(props);
    this.state = {
      uuid: GenerateUUID(),
      newDataId: GenerateUUID32(),
      childrens: props.children
      // provideItemAddList: []
    };
    this.id = this.getSearchName('id');
  }
  public static defaultProps = new Props();

  // 但官方并不推荐使用 UNSAFE_componentWillReceiveProps
  public UNSAFE_componentWillReceiveProps(newProps: any) {
    const { children } = this.props;
    if (children !== newProps.children) {
      this.setState({ childrens: newProps.children });
    }
  }

  componentDidMount() {
    if (this.props.form) {
      this.props.form.setSubmitCallback(this.saveData);
    }
  }

  UNSAFE_componentWillMount() {
    // 监听对应内容变化，进行对应操作
    this.props.setChildHandlers && this.props.setChildHandlers({
      onOrgChange: this.onOrgChange
    });
  }

  componentDidUpdate() {
    // this.setChildProps('provideItemAddList', {
    //   uuid: this.setUuid(),
    //   matterId: matterInfo.value,//关联事项id
    //   matterName: matterInfo.matterName,//关联事项名称
    //   matterTotal: matterInfo.matterTotal,//关联事项总金额
    //   matterTotalUseAble: matterInfo.matterTotalUseAble,//关联事项可用余额
    //   authorizeAmountUsable: projectInfo.descValue, //关联项目可用授权金额
    //   projectName: projectInfo.text
    // });
    // clearRouteBlocker();
    // console.log('prevProps.renderMode', prevProps.renderMode);
    // if (prevProps.renderMode === 'detail') return;
    // this.setDefaultValue();
    // console.log('online-official', this.props);
  }

  getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  }

  setDefaultValue = () => {
    if (this.id || !this.props.form) return;
    // const orgId = this.props.form.getFieldsValue()?.orgId;
    // const userInfo = this.props.userInfo?.user;
    // if (!orgId && userInfo) {
    //   // 设置默认部门
    //   const orgInfo = {
    //     value: userInfo.orgId,
    //     text: userInfo.orgName,
    //     type: 1
    //   };
    //   this.props.form.setFieldsValue({
    //     orgId: orgInfo
    //   });
    // }
    // const documentType = this.props.form.getFieldsValue()?.documentType;
    // if (!documentType) {
    //   // 设置默认公文类型
    //   this.props.form.setFieldsValue({
    //     documentType: { text: DOCUMENT_TYPE_LIST[0].label, value: DOCUMENT_TYPE_LIST[0].value }
    //   });
    // }
    // const ccUserList = this.props.form.getFieldsValue()?.ccUserList;
    // if (!ccUserList?.length) {
    //   // 设置默认抄送人
    //   this.props.form.setFieldsValue({
    //     ccUserList: [{ text: userInfo?.userName, value: userInfo?.userId, type: 2 }]
    //   });
    // }
    // const matterAddList = this.props.form.getFieldsValue()?.matterAddList;
    // if (matterAddList) {
    //   this.props.form.setFieldsValue({
    //     matterAddList
    //   });
    // }
  }

  onOrgChange = (val) => {
    if (!val) return;
    this.props.form?.setFieldsValue({
      documentName: `${val.text}党政联席会会议纪要`
    });
  }

  // 通过路由信息获取是否在修改草稿/重新提交 页面
  isResubmit = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('resubmit?') > -1;
    return isEmitMode;
  };

  setUuid = () => {
    const status = Number(this.getSearchName('status'));
    const dataId = this.getSearchName('applyId');
    const resubmit = this.getSearchName('resubmit');
    let uid = status !== APPROVAL_STATUS.Revert ? dataId : this.state.newDataId;
    if (resubmit === 'true' && status !== APPROVAL_STATUS.Draft) {
      uid = this.state.newDataId;
    }
    if (resubmit === '') {
      uid = this.state.newDataId;
    }
    return uid;
  }

  saveData = async () => {
    return new Promise((resolve, reject) => {
      const tmpFn = async () => {
        if (!this.props.form) {
          reject('form不存在');
        }
        const values = await this.props.form
          .validateFields()
          .catch((err: any) => {
            if (err && err.errors) {
              for (const key in err.errors) {
                const errMsg = err.errors[key]?.errors?.[0].message;
                Toast.fail(errMsg);
                return;
              }
            }
            // reject(err);
          });
        if (!values) return;
        const attachmentIds = values?.file?.map((item: any) => item);
        // return console.log('values', values);
        const status = this.getSearchName('status');
        const dataId = this.getSearchName('applyId');
        // 重新提交需重新生成 dataId
        const oldDataId = this.isResubmit() && status == 1 ? {
          oldDataId: dataId
        } : {};
        if (values.provideItemAddList) {
          delete values.provideItemAddList;
        }

        let triScopeInfo = values?.triScopeInfo || [];
        // 兼容老数据报错: triScopeInfo：{text:"",value:""}
        if (!Array.isArray(triScopeInfo) && triScopeInfo?.text) {
          triScopeInfo = [triScopeInfo];
        }
        if (values) {
          values.triScope = {
            value: Array.isArray(triScopeInfo) &&
              triScopeInfo?.map((item: any) => item.value).join(','),
            text: Array.isArray(triScopeInfo) &&
              triScopeInfo?.map((item: any) => item.text).join(',')
          };
        }

        resolve({
          result: true,
          data: {
            formValues: values,
            extra: {
              applyType: applyType.ONLINE_DOCUMENT_APPLY,
              dataId: this.setUuid(),
              applyName: decodeURIComponent(this.getSearchName('title')),
              extText: {
                orgId: this.getSearchName('orgId'), // history.getCurrentLocation().query.orgId,
                provideItemAddList: [],
                attachmentIds
              },
              ...oldDataId
            }
          }
        });
      };
      tmpFn();
    });
  };

  /**
   * 根据code设置对应child的props，
   * @param code 对应控件code
   * @param cellProps props传参
   */
  public setChildProps = (code: string, cellProps: CellProps) => {
    const { childrens } = this.state;
    childrens.forEach((child: any) => {
      if (!child?.props?.viewport?.instances) return;
      child.props.viewport.instances.forEach((item: any) => {
        if (item.data.props.code === code) {
          item.data.props = { ...item.data.props, ...cellProps };
          return;
        }
      });
    });
    this.setState({ childrens, uuid: GenerateUUID() });
  };

  public render() {
    const {
      childrens,
      uuid
    } = this.state;
    return (
      <div key={uuid}>
        {childrens}
      </div>
    );
  }
}

export const GroupOfficialOnline = connect(
  ({ common }: ConnectState) => ({
    userInfo: common.userInfo
  })
)(GroupOfficialOnlineCpt);
